using Kickball.Step1;
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

namespace Kickball.Step2
{
    [UpdateBefore(typeof(TransformSystemGroup))]
    public partial struct PlayerMovementSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.PlayerMovement>();
            state.RequireForUpdate<Config>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var config = SystemAPI.GetSingleton<Config>();

            //输入
            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");
            float3 input = new float3(horizontal, 0, vertical) * SystemAPI.Time.DeltaTime * config.PlayerSpeed;

            if (input.Equals(float3.zero)) return;

            float playerRadius = 0.5f;
            float minDist = config.ObstacleRadius + playerRadius;
            float minDistSq = minDist * minDist;

            foreach (var playerTrans in SystemAPI.Query<RefRW<LocalTransform>>().WithAll<Player>())
            {
                float3 pos = playerTrans.ValueRO.Position + input; //计算位移
                foreach (var obstacleTrans in SystemAPI.Query<RefRO<LocalTransform>>().WithAll<Obstacle>())
                {
                    if (math.distancesq(obstacleTrans.ValueRO.Position, pos) < minDistSq) //障碍碰撞
                    {
                        pos = playerTrans.ValueRO.Position;
                        break;
                    }
                }

                playerTrans.ValueRW.Position = pos;
            }
        }
    }
}